/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.deib.se2.meteocal.gui;

import it.polimi.deib.se2.meteocal.business.boundary.CalendarManager;
import it.polimi.deib.se2.meteocal.business.boundary.UserManager;
import it.polimi.deib.se2.meteocal.business.entity.Calendar;
import it.polimi.deib.se2.meteocal.business.entity.User;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;


@Named
@RequestScoped
public class RegistrationBean {

    @Inject
    private Logger logger;
    
    @EJB
    private UserManager um;
    
    @EJB
    private CalendarManager cm;

    private User user;
    private Calendar calendar;

    public RegistrationBean() {
    }

    public User getUser() {
        if (user == null) {
            firstRun();
        }
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String register() {
        FacesContext context = FacesContext.getCurrentInstance();
        if(um.find(user.getEmail()) == null) {
            um.save(user);
            user.setCalendar(getCalendar());
            cm.save(getCalendar());
            um.edit(user);
            return "user/home?faces-redirect=true";
        } else {
            context.addMessage(null, new FacesMessage("Upload a csv file"));
            return null;
        }
    }

    private void firstRun() {
        user = new User();
        calendar = new Calendar();
        setCalendar(calendar);
        
        getCalendar().setId(System.currentTimeMillis());
        getCalendar().setIsPublic(false);
        getCalendar().setMailNotification(true);
        getCalendar().setOwner(user);
    }

    /**
     * @return the calendar
     */
    public Calendar getCalendar() {   
        return calendar;
    }

    /**
     * @param calendar the calendar to set
     */
    public void setCalendar(Calendar calendar) {
        this.calendar = calendar;
    }

}
